package com.guaoran.interview.in23.collection.map;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author gucheng
 * @Description
 *    重写 {@link LinkedHashMap#removeEldestEntry(Map.Entry)} 来实现 LRU 淘汰策略
 * 2019-03-18 9:30
 */
public class LinkedHashMapLRU<K,V> extends LinkedHashMap<K,V> {
    private int initialCapacity;

    public LinkedHashMapLRU(int initialCapacity, float loadFactor) {
        super(initialCapacity, loadFactor, true);
        this.initialCapacity  = initialCapacity;
    }


    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        if(size() > this.initialCapacity){
            System.out.println(eldest + "删除了");
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        Map<String,Integer> sortMapLRU = new LinkedHashMapLRU<String,Integer>(16,0.75f);
        for (int i = 0; i < 10; i++) {
            sortMapLRU.put("key"+i,i);
        }
        sortMapLRU.entrySet().forEach(m ->{
            System.out.println(m.getKey()+" -> "+m.getValue());
        });
        System.out.println(sortMapLRU.get("key9"));
        System.out.println(sortMapLRU.get("key5"));
        System.out.println(sortMapLRU.get("key3"));

        sortMapLRU.entrySet().forEach(m ->{
            System.out.println(m.getKey()+" -> "+m.getValue());
        });

        System.out.println("LRU.....................start");
        for (int i = 10; i < 20; i++) {
            sortMapLRU.put("key"+i,i);
        }

        sortMapLRU.entrySet().forEach(m ->{
            System.out.println(m.getKey()+" -> "+m.getValue());
        });
    }
}
